package com.wzw.expression.expression.invocation;

import com.wzw.expression.expression.operation.Operation;
import org.springframework.context.expression.AnnotatedElementKey;
import org.springframework.lang.Nullable;

import java.lang.reflect.Method;

/**
 * @author Wangzhiwen
 */
public class OperationInvocationCacheKey implements Comparable<OperationInvocationCacheKey> {
    private final Operation operation;

    private final AnnotatedElementKey methodCacheKey;

    public OperationInvocationCacheKey(Operation operation, Method method, Class<?> targetClass) {
        this.operation = operation;
        this.methodCacheKey = new AnnotatedElementKey(method, targetClass);
    }

    @Override
    public boolean equals(@Nullable Object other) {
        return (this == other || (other instanceof OperationInvocationCacheKey that &&
                this.operation.equals(that.operation) &&
                this.methodCacheKey.equals(that.methodCacheKey)));
    }

    @Override
    public int hashCode() {
        return (this.operation.hashCode() * 31 + this.methodCacheKey.hashCode());
    }

    @Override
    public String toString() {
        return this.operation + " on " + this.methodCacheKey;
    }

    @Override
    public int compareTo(OperationInvocationCacheKey other) {
        int result = this.operation.getName().compareTo(other.operation.getName());
        if (result == 0) {
            result = this.methodCacheKey.compareTo(other.methodCacheKey);
        }
        return result;
    }
}
